package access

import (
	"api/config"
	"api/libs/errs"
	"encoding/base64"
	"fmt"
	"gitee.com/dreamwood/ez"
	"strconv"
	"strings"
)

const UserInfoKey = "EZ_USER_INFO:{%s}"

func CreateUserRedisKey(token string) string {
	return fmt.Sprintf(UserInfoKey, token)
}

func GetUserIdFromToken(token string) int {
	bt, e := base64.StdEncoding.DecodeString(token)
	if errs.Try(e) {
		return 0
	}
	data := ez.AesDecrypt(string(bt), config.GetCore().Vi)
	tmp := strings.Fields(data)
	if len(tmp) == 0 {
		return 0
	}
	id, e := strconv.Atoi(tmp[0])
	if errs.Try(e) {
		return 0
	}
	return id
}

func GetUserRoleIdFromToken(token string) []int {
	bt, e := base64.StdEncoding.DecodeString(token)
	if errs.Try(e) {
		return []int{0}
	}
	data := ez.AesDecrypt(string(bt), config.GetCore().Vi)
	tmp := strings.Fields(data)
	if len(tmp) == 0 {
		return []int{0}
	}
	ids := make([]int, 0)
	for _, str := range tmp[2:] {
		id, err := strconv.Atoi(str)
		if errs.Try(err) {
			return []int{0}
		}
		ids = append(ids, id)
	}
	return ids
}
